package com.sunshuo.springsecuritydemo.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.sunshuo.springsecuritydemo.pojo.VerifyCodeImage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @ClassName VerifyCodeController
 * @Description 验证码Controller
 * @Author sunshuo
 * @Date 2021/11/7 15:40
 */
@RestController
public class VerifyCodeController {

    /**
     * 验证码生成器
     */
    private DefaultKaptcha defaultKaptcha;

    @Autowired
    public void setDefaultKaptcha(DefaultKaptcha defaultKaptcha) {
        this.defaultKaptcha = defaultKaptcha;
    }

    /**
     * 请求验证码
     * @param session
     * @param response
     */
    @RequestMapping(value = "/verify_image", method = RequestMethod.GET)
    public void verifyCode(HttpSession session, HttpServletResponse response) throws IOException {
        /* 设置响应头 */
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        /* 生成验证码文本 */
        String verifyText = defaultKaptcha.createText();
        /* 设置验证码过期时间 */
        session.setAttribute("SESSION_VERIFY_CODE_IMAGE_KEY", new VerifyCodeImage(verifyText, 2 * 60));
        /* 响应验证码 */
        ServletOutputStream outputStream = response.getOutputStream();
        BufferedImage image = defaultKaptcha.createImage(verifyText);
        ImageIO.write(image, "jpg", outputStream);
        outputStream.flush();
    }

}
